<template>
  <div class="revenue-list page-container">
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">每日营业收入明细</h1>
        <p class="page-subtitle">查看和筛选每日营业收入明细记录</p>
      </div>
      <el-button type="primary" class="add-btn" @click="openAddDialog">
        <svg class="btn-icon" viewBox="0 0 24 24" fill="currentColor">
          <path d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z" />
        </svg>
        新增收入
      </el-button>
    </div>
    <el-config-provider :locale="zhCn">
      <div class="content-card">
        <div class="search-section">
          <el-date-picker
            v-model="searchForm.recordTime"
            type="date"
            placeholder="交易日期"
            class="search-input"
            clearable
          />
          <el-select
            v-model="searchForm.theFirst"
            placeholder="初/老顾客"
            clearable
            class="status-select"
          >
            <el-option label="全部" :value="''" />
            <el-option label="新客" :value="1" />
            <el-option label="老顾客" :value="2" />
          </el-select>
          <el-input
            v-model="searchForm.therapist"
            placeholder="治疗师"
            class="search-input"
            clearable
          />
          <el-input
            v-model="searchForm.customerName"
            placeholder="顾客姓名"
            class="search-input"
            clearable
          />
          <el-select
            v-model="searchForm.project"
            placeholder="项目类型"
            clearable
            class="status-select"
          >
            <el-option label="全部" :value="''" />
            <el-option label="体验" value="体验" />
            <el-option label="单次" value="单次" />
            <el-option label="年卡" value="年卡" />
            <el-option label="福利卡" value="福利卡" />
            <el-option label="疗程" value="疗程" />
          </el-select>
          <el-date-picker
            v-model="createdTimeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="入账时间-起"
            end-placeholder="入账时间-止"
            class="search-input"
            clearable
          />
        </div>
        <div class="search-section search-btn-row">
          <div style="flex: 1"></div>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </div>
        <el-table
          :data="revenueList"
          :loading="loading"
          style="width: 100%"
          class="revenue-table"
          highlight-current-row
        >
          <el-table-column prop="recordTime" label="交易日期" width="140" />
          <el-table-column prop="theFirst" label="初/老客" width="80">
            <template #default="scope">
              <el-tag
                :type="
                  scope.row.theFirst === 1
                    ? 'success'
                    : scope.row.theFirst === 2
                    ? 'warning'
                    : 'info'
                "
                size="small"
              >
                {{
                  scope.row.theFirst === 1
                    ? "新客"
                    : scope.row.theFirst === 2
                    ? "老顾客"
                    : ""
                }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="therapist" label="治疗师" width="100" />
          <el-table-column prop="customerName" label="顾客姓名" width="120" />
          <el-table-column prop="project" label="项目类型" width="100">
            <template #default="scope">
              <el-tag
                :type="
                  scope.row.project === '体验'
                    ? 'info'
                    : scope.row.project === '单次'
                    ? 'primary'
                    : scope.row.project === '年卡'
                    ? 'success'
                    : scope.row.project === '福利卡'
                    ? 'warning'
                    : 'default'
                "
                size="small"
              >
                {{ scope.row.project }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="projectDetail" label="项目明细" width="200" />
          <el-table-column prop="paymentType" label="支付方式" width="100">
            <template #default="scope">
              <el-tag
                :type="
                  scope.row.paymentType === '微信'
                    ? 'success'
                    : scope.row.paymentType === '支付宝'
                    ? 'primary'
                    : scope.row.paymentType === '现金'
                    ? 'danger'
                    : scope.row.paymentType === '抖音'
                    ? 'warning'
                    : scope.row.paymentType === '美团/大众'
                    ? 'info'
                    : scope.row.paymentType === '工行码'
                    ? 'default'
                    : scope.row.paymentType === 'POS机'
                    ? 'info'
                    : 'default'
                "
                size="small"
              >
                {{ scope.row.paymentType }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="paymentAmount" label="支付金额" width="100">
            <template #default="scope">
              <span class="amount">¥{{ scope.row.paymentAmount }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="createdTime" label="入账时间" width="160" />
          <el-table-column prop="remarks" label="备注" width="120" />
          <el-table-column label="操作" width="120">
            <template #default="scope">
              <el-button
                size="small"
                type="primary"
                @click="openEditDialog(scope.row)"
                >编辑</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="searchForm.pageIndex"
            v-model:page-size="searchForm.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-config-provider>

    <!-- 新建/编辑弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogMode === 'add' ? '新增收入明细' : '编辑收入明细'"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        :model="dialogForm"
        :rules="dialogRules"
        ref="dialogFormRef"
        label-width="100px"
        status-icon
      >
        <el-form-item label="交易日期" prop="recordTime">
          <el-date-picker
            v-model="dialogForm.recordTime"
            type="date"
            placeholder="选择日期"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item
          v-if="dialogMode === 'edit'"
          label="初/老顾客"
          prop="theFirst"
        >
          <el-select v-model="dialogForm.theFirst" placeholder="请选择">
            <el-option label="新客" :value="1" />
            <el-option label="老顾客" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="治疗师" prop="therapist">
          <el-select v-model="dialogForm.therapist" placeholder="请选择治疗师">
            <el-option
              v-for="item in therapistOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="顾客姓名" prop="customerName">
          <el-input
            v-model="dialogForm.customerName"
            placeholder="请输入顾客姓名"
          />
        </el-form-item>
        <el-form-item label="项目类型" prop="project">
          <el-select v-model="dialogForm.project" placeholder="请选择">
            <el-option label="体验" value="体验" />
            <el-option label="单次" value="单次" />
            <el-option label="年卡" value="年卡" />
            <el-option label="福利卡" value="福利卡" />
            <el-option label="疗程" value="疗程" />
            <el-option label="产品" value="产品" />
          </el-select>
        </el-form-item>
        <el-form-item label="项目明细" prop="projectDetail">
          <el-input
            v-model="dialogForm.projectDetail"
            placeholder="请输入项目明细"
          />
        </el-form-item>
        <el-form-item label="支付方式" prop="paymentType">
          <el-select v-model="dialogForm.paymentType" placeholder="请选择">
            <el-option label="微信" value="微信" />
            <el-option label="支付宝" value="支付宝" />
            <el-option label="抖音" value="抖音" />
            <el-option label="美团/大众" value="美团/大众" />
            <el-option label="工行码" value="工行码" />
            <el-option label="POS机" value="POS机" />
            <el-option label="现金" value="现金" />
          </el-select>
        </el-form-item>
        <el-form-item label="支付金额" prop="paymentAmount">
          <el-input
            v-model.number="dialogForm.paymentAmount"
            placeholder="请输入金额"
            type="number"
            min="0"
            step="0.01"
            @input="onAmountInput"
            @blur="onAmountBlur"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="dialogForm.remarks" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          :loading="dialogLoading"
          @click="handleDialogConfirm"
          >{{ dialogMode === "add" ? "新增" : "保存" }}</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { postWithAuth } from "@/utils/request";
import dayjs from "dayjs";
import zhCn from "element-plus/dist/locale/zh-cn.mjs";
import { ElConfigProvider } from "element-plus";

interface RevenueRecord {
  id: string;
  recordTime: string;
  theFirst: number;
  therapist: string;
  customerName: string;
  project: string;
  projectDetail: string;
  paymentType: string;
  paymentAmount: number;
  phone: string | null;
  wechat: string | null;
  remarks: string | null;
  createdTime: string;
  createdBy: string;
  createdByName: string | null;
  modifiedTime: string;
  modifiedBy: string;
  modifiedByName: string | null;
}

const loading = ref(false);
const revenueList = ref<RevenueRecord[]>([]);
const total = ref(0);
const createdTimeRange = ref<[string, string] | null>(null);
const searchForm = reactive({
  recordTime: null as string | null,
  theFirst: "" as string | number,
  therapist: "",
  customerName: "",
  project: "",
  createdTimeBegin: "",
  createdTimeEnd: "",
  pageIndex: 1,
  pageSize: 10,
});

const fetchRevenueList = async () => {
  loading.value = true;
  try {
    const params: any = {
      ...searchForm,
      pageIndex: searchForm.pageIndex,
      pageSize: searchForm.pageSize,
    };
    // 日期格式化
    if (searchForm.recordTime) {
      params.recordTime = dayjs(searchForm.recordTime).format("YYYY-MM-DD");
    }
    if (createdTimeRange.value && createdTimeRange.value.length === 2) {
      params.createdTimeBegin = dayjs(createdTimeRange.value[0])
        .startOf("day")
        .format("YYYY-MM-DD HH:mm:ss");
      params.createdTimeEnd = dayjs(createdTimeRange.value[1])
        .endOf("day")
        .format("YYYY-MM-DD HH:mm:ss");
    } else {
      params.createdTimeBegin = "";
      params.createdTimeEnd = "";
    }
    const res = await postWithAuth("/internal/revenueRecord/pageList", params);
    if (res.code === 0 && res.data) {
      revenueList.value = res.data.list || [];
      total.value = Number(res.data.total) || 0;
    } else {
      ElMessage.error(res.message || "获取收入明细失败");
    }
  } catch (e) {
    ElMessage.error("请求收入明细异常");
  } finally {
    loading.value = false;
  }
};

const handleSearch = () => {
  searchForm.pageIndex = 1;
  fetchRevenueList();
};

const resetSearch = () => {
  searchForm.recordTime = null;
  searchForm.theFirst = "";
  searchForm.therapist = "";
  searchForm.customerName = "";
  searchForm.project = "";
  createdTimeRange.value = null;
  searchForm.pageIndex = 1;
  fetchRevenueList();
};

const handleSizeChange = (val: number) => {
  searchForm.pageSize = val;
  searchForm.pageIndex = 1;
  fetchRevenueList();
};

const handleCurrentChange = (val: number) => {
  searchForm.pageIndex = val;
  fetchRevenueList();
};

const dialogVisible = ref(false);
const dialogMode = ref<"add" | "edit">("add");
const dialogLoading = ref(false);
const dialogFormRef = ref();
const dialogForm = reactive({
  id: "",
  recordTime: "",
  theFirst: "",
  therapist: "",
  customerName: "",
  project: "",
  projectDetail: "",
  paymentType: "",
  paymentAmount: 0 as number, // 明确为number类型
  remarks: "",
});
const dialogRules = {
  recordTime: [
    { required: true, message: "请选择交易日期", trigger: "change" },
  ],
  theFirst: [{ required: true, message: "请选择初/老顾客", trigger: "change" }],
  therapist: [{ required: true, message: "请输入治疗师", trigger: "blur" }],
  customerName: [
    { required: true, message: "请输入顾客姓名", trigger: "blur" },
  ],
  project: [{ required: true, message: "请选择项目类型", trigger: "change" }],
  projectDetail: [
    { required: true, message: "请输入项目明细", trigger: "blur" },
  ],
  paymentType: [
    { required: true, message: "请选择支付方式", trigger: "change" },
  ],
  paymentAmount: [
    { required: true, message: "请输入支付金额", trigger: "blur" },
  ],
};

const therapistOptions = [
  { label: "欣欣", value: "欣欣" },
  { label: "小美", value: "小美" },
  { label: "小李", value: "小李" },
  // 可根据实际添加更多
];

function openAddDialog() {
  dialogMode.value = "add";
  Object.assign(dialogForm, {
    id: "",
    recordTime: dayjs().toDate(),
    // theFirst: '', // 新增不需要初/老顾客
    therapist: "欣欣",
    customerName: "",
    project: "体验", // 默认选中体验
    projectDetail: "",
    paymentType: "",
    paymentAmount: 0,
    remarks: "",
  });
  dialogVisible.value = true;
}

function openEditDialog(row: RevenueRecord) {
  dialogMode.value = "edit";
  Object.assign(dialogForm, {
    ...row,
    recordTime: row.recordTime ? dayjs(row.recordTime).toDate() : "",
  });
  dialogVisible.value = true;
}

async function handleDialogConfirm() {
  if (!dialogFormRef.value) return;
  await dialogFormRef.value.validate();
  dialogLoading.value = true;
  try {
    const submitData = {
      ...dialogForm,
      recordTime: dialogForm.recordTime
        ? dayjs(dialogForm.recordTime).format("YYYY-MM-DD")
        : "",
    };
    if (dialogMode.value === "add") {
      // 新增接口，不传theFirst
      const { theFirst, ...addParams } = submitData;
      await postWithAuth("/internal/revenueRecord/addRevenueRecord", addParams);
      ElMessage.success("新增成功");
    } else {
      // 编辑接口，保留theFirst
      await postWithAuth(
        "/internal/revenueRecord/modifyRevenueRecord",
        submitData
      );
      ElMessage.success("保存成功");
    }
    dialogVisible.value = false;
    fetchRevenueList();
  } catch (e) {
    ElMessage.error("操作失败");
  } finally {
    dialogLoading.value = false;
  }
}

function onAmountBlur() {
  // 只需判断是否为数字
  const val = Number(dialogForm.paymentAmount);
  if (!isNaN(val)) {
    dialogForm.paymentAmount = Math.round(val * 100) / 100;
  } else {
    dialogForm.paymentAmount = 0;
  }
}

function onAmountInput(val: string | number) {
  // 只允许输入两位小数
  let str = String(val);
  if (str.includes(".")) {
    const [intPart, decPart] = str.split(".");
    if (decPart.length > 2) {
      str = intPart + "." + decPart.slice(0, 2);
      dialogForm.paymentAmount = Number(str);
    }
  }
}

onMounted(() => {
  fetchRevenueList();
});
</script>

<style scoped>
.revenue-list {
  padding: 24px;
  background: #f5f7fa;
  min-height: 100vh;
}
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  /* background: white;
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06); */
}
.header-content {
  flex: 1;
}
.page-title {
  font-size: 28px;
  font-weight: 700;
  color: #2d3748;
  margin: 0 0 8px 0;
}
.page-subtitle {
  color: #718096;
  margin: 0;
  font-size: 16px;
}
.btn-icon {
  width: 16px;
  height: 16px;
}
.content-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}
.toolbar {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 16px;
}
.search-section {
  display: flex;
  flex-wrap: wrap;
  gap: 16px 12px;
  margin-bottom: 24px;
  align-items: flex-end;
}
.search-section .el-input,
.search-section .el-select,
.search-section .el-date-picker {
  min-width: 100px;
  max-width: 140px;
  flex: none;
}
.search-section .el-date-picker[placeholder*="入账时间"],
.search-section .el-date-picker[placeholder*="入账时间-起"],
.search-section .el-date-picker[placeholder*="入账时间-止"] {
  min-width: 100px !important;
  max-width: 140px;
}
.search-section .el-button {
  min-width: 96px;
  margin-left: 12px;
  padding-left: 0;
  padding-right: 0;
}
.search-input {
  flex: 1;
  max-width: 200px;
}
.status-select {
  width: 120px;
}
.revenue-table {
  margin-bottom: 24px;
  /* 去除表格线条 */
  border: none !important;
}
.revenue-table .el-table__cell,
.revenue-table .el-table__header-wrapper,
.revenue-table .el-table__body-wrapper {
  border: none !important;
}
.revenue-table .el-table__row > td {
  border-bottom: none !important;
}
.amount {
  font-weight: 600;
  color: #e53e3e;
}
.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 24px;
}
.el-dialog__body {
  padding-top: 12px;
  padding-bottom: 0;
}
.el-form-item {
  margin-bottom: 18px;
}
.el-dialog__footer {
  padding-top: 0;
}
.el-table th,
.el-table td {
  font-size: 15px;
}
.el-table .el-button {
  padding: 4px 10px;
  font-size: 13px;
}
.el-table .amount {
  color: #e53e3e;
  font-weight: 600;
}
.el-table .el-table__cell {
  background: #fcfcfc;
}
.el-table .el-table__row:hover > td {
  background: #f0f7ff !important;
}
.add-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 15px;
  font-weight: 500;
  padding: 8px 18px;
  border-radius: 8px;
  background: linear-gradient(90deg, #409eff 0%, #66b1ff 100%);
  color: #fff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.08);
  border: none;
  transition: background 0.2s;
}
.add-btn:hover {
  background: linear-gradient(90deg, #66b1ff 0%, #409eff 100%);
}
.search-section.search-btn-row {
  margin-top: -8px;
  gap: 0 12px;
  justify-content: flex-end;
}
@media (max-width: 1024px) {
  .revenue-list {
    padding: 20px;
  }
  .page-header {
    padding: 20px;
  }
  .page-title {
    font-size: 24px;
  }
  .page-subtitle {
    font-size: 14px;
  }
  .content-card {
    padding: 20px;
  }
  .search-section {
    gap: 12px 8px;
  }
  .search-section .el-input,
  .search-section .el-select,
  .search-section .el-date-picker {
    min-width: 100px;
    max-width: 120px;
  }
  .search-section .el-date-picker[placeholder*="入账时间"],
  .search-section .el-date-picker[placeholder*="入账时间-起"],
  .search-section .el-date-picker[placeholder*="入账时间-止"] {
    min-width: 100px !important;
    max-width: 120px;
  }
}
@media (max-width: 768px) {
  .revenue-list {
    padding: 16px;
  }
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
    padding: 20px;
  }
  .page-title {
    font-size: 20px;
    margin-bottom: 6px;
  }
  .page-subtitle {
    font-size: 13px;
  }
  .content-card {
    padding: 16px;
    border-radius: 10px;
  }
  .search-section {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }
  .search-section .el-input,
  .search-section .el-select,
  .search-section .el-date-picker {
    min-width: 0;
    max-width: 100%;
    width: 100%;
    box-sizing: border-box;
    height: 40px;
    /* 统一高度 */
  }
  .search-section .el-date-picker[placeholder*="入账时间"],
  .search-section .el-date-picker[placeholder*="入账时间-起"],
  .search-section .el-date-picker[placeholder*="入账时间-止"] {
    min-width: 0 !important;
    max-width: 100%;
    width: 100%;
    box-sizing: border-box;
    height: 40px;
  }
  .search-section .el-button {
    margin-left: 0;
    width: 100%;
    min-width: 0;
    height: 40px;
  }
  .search-input {
    max-width: none;
    width: 100%;
    height: 40px;
  }
  .status-select {
    width: 100%;
    height: 40px;
  }
  .revenue-table {
    margin-bottom: 20px;
  }
  .pagination-wrapper {
    margin-top: 20px;
  }
}
</style>
